package controller;


import dao.impl.UserDaoImpl;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得参数
        String username = req.getParameter("username");
        String password = req.getParameter("pwd");
        //调用service对象执行登录
        UserDaoImpl userService = new UserDaoImpl();
        try {
            User user = userService.login(username, password);
            if(user == null){
                //将错误信息保存到request对象
                req.setAttribute("error","账号或密码错误");
                //如果登录失败，请求转发到登录页面
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }else{
                //将用户对象保存到session对象
                req.getSession().setAttribute("user",user);
                //如果登录成功，重定向到查询宠物的servlet
                resp.sendRedirect("selectAllPhone.do");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
